import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:jtlf/collaboration/meeting/meeting_detail.dart';
import 'package:jtlf/collaboration/task/task_detail.dart';

class CollaborationPage extends StatefulWidget {
  @override
  _CollaborationPageState createState() => _CollaborationPageState();
}

class _CollaborationPageState extends State<CollaborationPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final ScrollController _scrollController = ScrollController();
  final List<String> _tabs = ['任务', '文档', '会议'];
  double _elevation = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
    _scrollController.addListener(_scrollListener);
  }

  void _scrollListener() {
    setState(() {
      _elevation = _scrollController.offset > 0 ? 1 : 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: _showCreateMenu,
        tooltip: '新建项目',
      ),
      body: NestedScrollView(
        controller: _scrollController,
        headerSliverBuilder: (context, innerBoxScrolled) => [
          // 这个是顶部的菜单栏，现在先去掉 2025-03-15
          SliverAppBar(
            // title: Text('项目协作中心'), // 去掉标题，标题很占高度
            toolbarHeight: 0, // 设置为高度是0，那么就不会占很高的高度了
            pinned: true,
            floating: true,
            forceElevated: true,
            elevation: _elevation,
            bottom: TabBar(
              controller: _tabController,
              tabs: _tabs.map((e) => Tab(text: e)).toList(),
              labelColor: Colors.blue,
              unselectedLabelColor: Colors.grey,
              indicatorSize: TabBarIndicatorSize.label,
            ),
          ),
        ],
        body: TabBarView(
          controller: _tabController,
          children: [
            _buildTaskView(),
            _buildDocumentView(),
            _buildMeetingView(),
          ],
        ),
      ),
    );
  }

  // 任务视图
  Widget _buildTaskView() {
    return ListView.builder(
      padding: EdgeInsets.all(16),
      itemCount: demoTasks.length,
      itemBuilder: (context, index) => _buildTaskItem(demoTasks[index]),
    );
  }

  Widget _buildTaskItem(Task task) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: ListTile(
        leading: Checkbox(
          value: task.completed,
          onChanged: (v) => _toggleTask(task),
        ),
        title: Text(task.title,
            style: TextStyle(
                decoration: task.completed ? TextDecoration.lineThrough : null)),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(task.description),
            SizedBox(height: 4),
            Row(
              children: [
                Icon(Icons.calendar_today, size: 14),
                SizedBox(width: 4),
                Text(task.dueDate),
              ],
            ),
          ],
        ),
        trailing: _buildTaskPriority(task.priority),
        onTap: () => _openTaskDetail(task),
      ),
    );
  }

  // 文档视图
  Widget _buildDocumentView() {
    return GridView.builder(
      padding: EdgeInsets.all(16),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        childAspectRatio: 0.8,
      ),
      itemCount: demoDocuments.length,
      itemBuilder: (context, index) => _buildDocumentCard(demoDocuments[index]),
    );
  }

  Widget _buildDocumentCard(Document document) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () => _openDocument(document),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
                ),
                alignment: Alignment.center,
                child: Icon(Icons.insert_drive_file, size: 48, color: Colors.blue),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(document.title,
                      style: TextStyle(fontWeight: FontWeight.bold)),
                  SizedBox(height: 4),
                  Row(
                    children: [
                      Icon(Icons.person, size: 14),
                      SizedBox(width: 4),
                      Text(document.author),
                    ],
                  ),
                  SizedBox(height: 4),
                  Text(document.modifiedTime),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 会议视图
  Widget _buildMeetingView() {
    return ListView.separated(
      padding: EdgeInsets.all(16),
      itemCount: demoMeetings.length,
      separatorBuilder: (_, __) => SizedBox(height: 12),
      itemBuilder: (context, index) => _buildMeetingItem(demoMeetings[index]),
    );
  }

  Widget _buildMeetingItem(Meeting meeting) {
    // return Card(
    //   shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
    //   child: ListTile(
    //     leading: Checkbox(
    //       value: meeting.completed,
    //       onChanged: (v) => _toggleTask(meeting),
    //     ),
    //     title: Text(meeting.title,
    //         style: TextStyle(
    //             decoration: meeting.completed ? TextDecoration.lineThrough : null)),
    //     subtitle: Column(
    //       crossAxisAlignment: CrossAxisAlignment.start,
    //       children: [
    //         Text(meeting.description),
    //         SizedBox(height: 4),
    //         Row(
    //           children: [
    //             Icon(Icons.calendar_today, size: 14),
    //             SizedBox(width: 4),
    //             Text(meeting.dueDate),
    //           ],
    //         ),
    //       ],
    //     ),
    //     trailing: _buildTaskPriority(meeting.priority),
    //     onTap: () => _openTaskDetail(meeting),
    //   ),
    // );
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      // 这是一个可展开的组件，其实不需要的，
      child: ListTile(
        leading: Icon(Icons.video_call, color: Colors.blue),
        title: Text(meeting.title),
        subtitle: Text(meeting.time),
        trailing: _buildMeetingStatus(meeting.status),
        onTap: () => {
          Navigator.of(context).push(MaterialPageRoute(builder: (context) => MeetingDetailPage()))
        },
        // children: [
        //   Padding(
        //     padding: EdgeInsets.all(16),
        //     child: Column(
        //       children: [
        //         Row(
        //           children: [
        //             Icon(Icons.link, size: 16),
        //             SizedBox(width: 8),
        //             SelectableText(meeting.link),
        //           ],
        //         ),
        //         SizedBox(height: 8),
        //         _buildParticipantAvatars(meeting.participants),
        //       ],
        //     ),
        //   ),
        // ],
      ),
    );
  }

  // 其他组件和交互方法
  Widget _buildTaskPriority(int priority) {
    final colors = [Colors.green, Colors.orange, Colors.red];
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: colors[priority].withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        ['低', '中', '高'][priority],
        style: TextStyle(color: colors[priority]),
      ),
    );
  }

  Widget _buildMeetingStatus(MeetingStatus status) {
    final colors = {
      MeetingStatus.upcoming: Colors.blue,
      MeetingStatus.inProgress: Colors.green,
      MeetingStatus.ended: Colors.grey,
    };
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: colors[status]!.withOpacity(0.1),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        status.toString().split('.').last,
        style: TextStyle(color: colors[status]),
      ),
    );
  }

  Widget _buildParticipantAvatars(List<Member> participants) {
    return Wrap(
      spacing: 8,
      children: participants
          .map((p) => CircleAvatar(
        radius: 16,
        backgroundImage: CachedNetworkImageProvider(p.avatar),
      ))
          .toList(),
    );
  }

  // 交互方法
  void _showCreateMenu() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildCreateItem('新建项目', Icons.create_new_folder, _createNewProject),
            _buildCreateItem('创建会议', Icons.videocam, _createMeeting),
            _buildCreateItem('发起任务', Icons.task, _createTask),
            _buildCreateItem('上传文档', Icons.upload_file, () {}),
          ],
        ),
      ),
    );
  }

  ListTile _buildCreateItem(String title, IconData icon, VoidCallback onTap) {
    return ListTile(
      leading: Icon(icon, color: Theme.of(context).primaryColor),
      title: Text(title),
      onTap: () {
        Navigator.pop(context);
        onTap();
      },
    );
  }

  void _toggleTask(Task task) => setState(() => task.completed = !task.completed);
  void _openTaskDetail(Task task) => {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) => TaskDetailPage()))
  };
  void _openDocument(Document doc) => _showSnackbar('打开文档: ${doc.title}');
  void _createNewProject() => _showSnackbar('新建项目');
  void _createMeeting() => {

  };
  void _createTask() => _showSnackbar('发起任务');

  void _showSnackbar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(message), duration: Duration(seconds: 1))
    );
  }
}

// 数据模型
class Task {
  String title;
  String description;
  String dueDate;
  int priority;
  bool completed;

  Task({
    required this.title,
    required this.description,
    required this.dueDate,
    this.priority = 0,
    this.completed = false,
  });
}

class Document {
  final String title;
  final String author;
  final String modifiedTime;

  Document({
    required this.title,
    required this.author,
    required this.modifiedTime,
  });
}

class Meeting {
  final String title;
  final String time;
  final String link;
  final MeetingStatus status;
  final List<Member> participants;

  Meeting({
    required this.title,
    required this.time,
    required this.link,
    required this.status,
    required this.participants,
  });
}

enum MeetingStatus { upcoming, inProgress, ended }

class Member {
  final String id;
  final String name;
  final String avatar;
  final String department;
  final String position;

  Member({
    required this.id,
    required this.name,
    required this.avatar,
    required this.department,
    required this.position,
  });
}

// 示例数据
final List<Task> demoTasks = [
  Task(
    title: '设计评审会议纪要整理',
    description: '整理上周设计评审会议的主要内容',
    dueDate: '2023-08-20',
    priority: 1,
  ),
  Task(
    title: '用户测试计划制定',
    description: '完成新版本用户测试方案',
    dueDate: '2023-08-25',
    priority: 2,
  ),
];

final List<Document> demoDocuments = [
  Document(
    title: '产品需求文档.docx',
    author: '张伟',
    modifiedTime: '2023-08-15 14:30',
  ),
  Document(
    title: '技术架构图.pdf',
    author: '李娜',
    modifiedTime: '2023-08-18 09:45',
  ),
];

final List<Meeting> demoMeetings = [
  Meeting(
    title: '项目启动会',
    time: '今天 14:00 - 15:30',
    link: 'https://meet.example.com/123',
    status: MeetingStatus.upcoming,
    participants: [
      Member(
          id: '1',
          name: '张伟',
          avatar: 'https://example.com/avatars/1.jpg',
          department: '产品部',
          position: '经理'
      ),
      Member(
          id: '2',
          name: '李娜',
          avatar: 'https://example.com/avatars/2.jpg',
          department: '技术部',
          position: '工程师'
      ),
    ],
  ),
];
